package oss

import (
	"fmt"
	"io"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

type Config struct {
	Endpoint string // 域名
	Key      string // key
	Secret   string // 密码
}

var client *oss.Client

func List() ([]string, error) {
	lsRes, err := client.ListBuckets()
	if err != nil {
		return nil, err
	}
	n := len(lsRes.Buckets)
	res := make([]string, n)
	for i := 0; i < n; i++ {
		bucket := lsRes.Buckets[i]
		res[i] = bucket.Name
	}
	return res, nil
}
func CreateBucket(bucket string) error {
	return client.CreateBucket(bucket)
}

func DeleteBucket(bucket string) error {
	return client.DeleteBucket(bucket)
}

func PutObject(bucket string, stream io.Reader) error {
	b, err := client.Bucket(bucket)
	if err != nil {
		return err
	}
	err = b.PutObject(bucket, stream)
	if err != nil {
		return err
	}
	return nil

}
func PutObjectFromFile(bucket string, objectPath string) error {
	b, err := client.Bucket(bucket)
	if err != nil {
		return err
	}

	err = b.PutObjectFromFile(bucket, objectPath)
	if err != nil {
		return err
	}
	return nil
}
func GetObjectFromFile(bucket string, objectPath string) error {
	b, err := client.Bucket(bucket)
	if err != nil {
		return err
	}

	err = b.GetObjectToFile(bucket, objectPath)
	if err != nil {
		return err
	}
	return nil
}

func ListObjects(bucket string, objectPath string) error {
	b, err := client.Bucket(bucket)
	if err != nil {
		return err
	}
	lsRes, err := b.ListObjects()
	if err != nil {
		return err
	}

	for _, object := range lsRes.Objects {
		fmt.Println("Objects:", object.Key)
	}
	return nil
}

func DeleteObjects(bucket string, object string) error {
	b, err := client.Bucket(bucket)
	if err != nil {
		return err
	}
	return b.DeleteObject(object)
}

func Init(config *Config) error {
	var err error
	client, err = oss.New(config.Endpoint, config.Key, config.Secret)
	if err != nil {
		return err
	}
	fmt.Println("oss config load success")
	return nil
}
